package com.wisemoresystem.seal.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ne.framework.data.page.Page;
import org.ne.framework.data.task.Task;
import org.ne.framework.data.util.ChkTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wisemoresystem.seal.base.service.BaseService;
import com.wisemoresystem.seal.model.t_check;
import com.wisemoresystem.seal.model.t_seal;
import com.wisemoresystem.seal.model.t_seal_new;
import com.wisemoresystem.seal.model.t_seal_new_factory_log;
import com.wisemoresystem.seal.model.t_seal_workflow;
import com.wisemoresystem.seal.model.t_seal_workflow_module;
import com.wisemoresystem.seal.web.WebTools;

@Service
public class SealNewService extends BaseService {

	@Autowired
	private CheckService checkService;
	@Autowired
	private VerifyConfigService configService;
	@Autowired
	private WorkflowService wkflowService;
	@Autowired
	private BankService bService;

	// 新章申请 新增时
	@Transactional
	public void apply(t_seal_new seal_new) {

		seal_new.setUser_id(WebTools.getCurrentUserId());
		seal_new.setUser_bank_id(WebTools.getCurrentBankId());
		seal_new.setUse_bank_id(seal_new.getBank_id());
		seal_new.setBank_id(WebTools.getCurrentBankId());
		super.saveObj(seal_new);

		if ("已保存".equals(seal_new.getFlag())) {
			return;
		}

		mySubmit(seal_new);
	}// #apply

	// 修改时
	@Transactional
	public void applyEdit(t_seal_new seal_new) {
		super.updateObj(seal_new);

		if ("已保存".equals(seal_new.getFlag())) {
			return;
		}

		mySubmit(seal_new);
	}

	// 提交部分
	@Transactional
	private void mySubmit(t_seal_new seal_new) {

		boolean isVerify = configService.isApplyStart();
		if (isVerify == true) {
			t_check check = new t_check();
			check.setBank_id(seal_new.getBank_id());
			check.setType("申请复核");
			check.setIs_verify("是");
			check.setVerify_bank_id(seal_new.getBank_id());
			check.setVerify("待审核");
			check.setUser_id(WebTools.getCurrentUserId());
			super.saveObj(check);

			seal_new.setFlag("待复核");
			seal_new.setCheck_id(check.get_id());
			super.updateObj(seal_new);
		} else {

			seal_new.setFlag("审核中");
			super.updateObj(seal_new);

			// 生成流程流转单
			wkflowService.wkflowApply(seal_new);
		}

	}

	// 印章复核
	@Transactional
	public void check(String seal_new_id, String flag, String note,boolean isTop) {
		t_seal_new seal_new = super.findObjById(seal_new_id, t_seal_new.class);
		t_check check = super
				.findObjById(seal_new.getCheck_id(), t_check.class);

		check.setVerify_user_id(WebTools.getCurrentUserId());
		check.setVerify(flag);
		check.setVerify_time(new Timestamp(System.currentTimeMillis()));
		check.setNote(note);
		if ("通过".equals(check.getVerify())) {
			if(isTop){
				seal_new.setFlag("已审核通过");
			}
			seal_new.setFlag("审核中");

			ht.update(seal_new);
			ht.update(check);

			// 生成流程流转单
			wkflowService.wkflowApply(seal_new);
		} else if ("不通过".equals(check.getVerify())) {

			seal_new.setFlag("已拒绝");

			ht.update(seal_new);
			ht.update(check);
		}

	}

	@Task(code = "seal_application1", tip = "未完成的新章申请(@cnt)")
	public long selectSealNewList() {
		String sql = "select count(*) cnt from t_seal_new t "
				+ " where t.status=0 and t.flag='已保存' and t.bank_id=? ";

		Long cnt = super.getTaskCnt(sql, WebTools.getCurrentBankId());
		
		return cnt;
	}

	// 查询印章申请列表
	public List<Map<String, Object>> selectSealNewList(String srh_name,
			Page page) {

		String sql = "select t.*,tb.name bank_name,tst.name seal_type_name,tstc.name seal_type_config_name from t_seal_new t "
				+ " left join t_bank tb on t.use_bank_id=tb._id "
				+ " left join t_seal_type tst on t.seal_type_id=tst._id "
				+ " left join t_seal_type_config tstc on t.seal_type_config_id=tstc._id "
				+ " where t.status=0 and t.flag='已保存' and tb.name like ? and t.bank_id=? "
				+ " order by t.created asc ";

		List<String> params = new ArrayList<String>();
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and tb.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		params.add(WebTools.getCurrentBankId());

		List<Map<String, Object>> list = jc.queryForList(sql, params.toArray(),
				page);
		return list;
	}

	@Task(code = "seal_application2", tip = "未完成的新章审核(@cnt)")
	public long selectSealNewApplyCheckingList() {
		String sql = "select count(*) cnt from t_seal_new t "
				+ " where t.status=0 and t.flag='待复核' and t.bank_id=? and t.user_id!=? ";

		Long cnt = super.getTaskCnt(sql, WebTools.getCurrentBankId(),WebTools.getCurrentUserId());
		
		return cnt;
	}
	
	// 查询 正在复核中的印章列表
	public List<Map<String, Object>> selectSealNewApplyCheckingList(
			String srh_name, Page page) {
		String sql = "select t.*,tb.name bname,ttype.name type_name,ttypeconfig.name type_config_name from t_seal_new t "
				+ " left outer join t_bank tb on t.bank_id=tb._id and tb.status=0 "
				+ " left outer join t_seal_type ttype on ttype._id=t.seal_type_id and ttype.status=0 "
				+ " left outer join t_seal_type_config ttypeconfig on t.seal_type_config_id=ttypeconfig._id and ttypeconfig.status=0 "
				+ " where t.status=0 and t.flag='待复核' and t.bank_id=? and t.user_id!=? order by t.created desc ";

		List<Map<String, Object>> list = jc.queryForList(sql,
				new String[] { WebTools.getCurrentBankId(),WebTools.getCurrentUserId() }, page);

		return list;

	}
	
	@Task(code = "seal_application4", tip = "未完成的新章审批(@cnt)")
	public long selectApplyingSealNewList() {
		String sql = "select count(*) cnt from t_seal_new t "
				+ " left outer join t_seal_workflow twk on t.workflow_id=twk._id and twk.status=0 and twk.type='新章审批' and twk.flag='进行中' "
				+ " left outer join  t_seal_workflow_module twkm on twk._id=twkm.workflow_id and twkm.status=0 and twkm.flag='待审批' "
				+ " where t.status=0 and t.flag='审核中' and twkm.verify_bank_id=? and t.user_id!=? ";

		Long cnt = super.getTaskCnt(sql, WebTools.getCurrentBankId(),WebTools.getCurrentUserId());
		
		return cnt;
	}

	// 查询 已经提交申请, 正在等待审批 的新章申请记录
	public List<Map<String, Object>> selectApplyingSealNewList(Page page) {

		String sql = "select t.*,tb.name bname,twk.created apply_created,ttype.name type_name,ttypeconfig.name type_config_name from t_seal_new t "
				+ " left outer join t_bank tb on t.bank_id=tb._id and tb.status=0 "
				+ " left outer join t_seal_type ttype on ttype._id=t.seal_type_id and ttype.status=0 "
				+ " left outer join t_seal_type_config ttypeconfig on t.seal_type_config_id=ttypeconfig._id and ttypeconfig.status=0 "
				+ " left outer join t_seal_workflow twk on t.workflow_id=twk._id and twk.status=0 and twk.type='新章审批' and twk.flag='进行中' "
				+ " left outer join  t_seal_workflow_module twkm on twk._id=twkm.workflow_id and twkm.status=0 and twkm.flag='待审批' "
				+ " where t.status=0 and t.flag='审核中' and twkm.verify_bank_id=? and t.user_id!=? order by t.created desc ";

		List<Map<String, Object>> list = jc.queryForList(sql,
				new String[] { WebTools.getCurrentBankId(),WebTools.getCurrentUserId() }, page);
		System.err.println(WebTools.getCurrentBankId());

		return list;
	}

	// 查询审批的 workflow module list
	public List<Map<String, Object>> selectModuleList(String workflow_id) {
		String sql = "select t.*,tb.name bname from t_seal_workflow_module t "
				+ " left outer join t_bank tb on t.verify_bank_id=tb._id and tb.status=0 "
				+ " where t.status=0 and t.workflow_id=? order by t.sort asc";
		List<Map<String, Object>> list = jt.queryForList(sql, workflow_id);

		return list;
	}

	// 查询剩余的 model 列表
	public List<t_seal_workflow_module> selectRestModuleList(
			String workflow_id, int pre_sort) {

		String hql = "from t_seal_workflow_module t where t.status=0 and t.workflow_id=? and t.sort>? order by t.sort asc";
		List<t_seal_workflow_module> list = (List<t_seal_workflow_module>) ht
				.find(hql, workflow_id, pre_sort);
		return list;
	}

	// 查询 本次 审核模块
	public t_seal_workflow_module selectThisModule(String workflow_id) {
		String hql = "from t_seal_workflow_module t where t.status=0 and t.workflow_id=? and t.flag='待审批' and t.verify_bank_id=? order by t.sort asc";
		t_seal_workflow_module module = super.findObj(hql, workflow_id,
				WebTools.getCurrentBankId());

		return module;
	}

	// 查询 下轮 审核模块
	public t_seal_workflow_module selectNextModule(String workflow_id,
			int pre_sort) {
		String hql = "from t_seal_workflow_module t where t.status=0 and t.workflow_id=? and t.sort=? order by t.sort asc";
		t_seal_workflow_module module = super.findObj(hql, workflow_id,
				pre_sort + 1);

		return module;
	}

	/**
	 * 新章审批 通过 不通过
	 * 
	 * @param seal_new
	 * @param flag
	 */
	@Transactional
	public void verify(String seal_new_id, String flag, String note) {
		t_seal_new seal_new = super.findObjById(seal_new_id, t_seal_new.class);
		t_seal_workflow wkflow = super.findObjById(seal_new.getWorkflow_id(),
				t_seal_workflow.class);

		t_seal_workflow_module module = this.selectThisModule(wkflow.get_id());

		module.setFlag(flag);
		module.setVerify_user_id(WebTools.getCurrentUserId());
		module.setVerify_bank_id(WebTools.getCurrentBankId());
		module.setVerify_time(new Timestamp(System.currentTimeMillis()));
		module.setNote(note);

		ht.update(module);

		if ("不通过".equals(flag)) {
			// 掐断流程
			List<t_seal_workflow_module> list = this.selectRestModuleList(
					wkflow.get_id(), module.getSort());
			for (t_seal_workflow_module restModule : list) {
				restModule.setFlag("已终止");
				ht.update(restModule);
			}

			// 终止 workflow
			wkflow.setFlag("已终止");
			ht.update(wkflow);

			seal_new.setFlag("已拒绝");
			ht.update(seal_new);

			return;
		}

		t_seal_workflow_module module_next = this.selectNextModule(
				wkflow.get_id(), module.getSort());
		if (module_next != null) {

			// 继续下一轮
			module_next.setFlag("待审批");
			ht.update(module_next);

		} else {
			// 流程完结处理

			// 终止 workflow
			wkflow.setFlag("已终止");
			ht.update(wkflow);

			seal_new.setFlag("已审核通过");
			ht.update(seal_new);

		}

	}

	@Task(code = "seal_engraving0", tip = "待刻章(@cnt)")
	public long selectSealNewListMy() {
		int lev = bService.getBankLevel(WebTools.getCurrentBankId());
		
		String sql = " select count(*) cnt from t_seal_new t "
				+ " left outer join t_seal_type_config tstc on t.seal_type_config_id=tstc._id and tstc.status=0 "
				+ " left join t_seal_workflow tw on t.workflow_id=tw._id "
				+ " left join t_seal_workflow_module tm on tm.workflow_id=tw._id "
				+ " left join t_bank_level tl on tstc.verify_new=tl.name "
				+ " where t.flag in ('已审核通过','待刻制') and t.status=0 and tl.sort>=? and tm.verify_bank_id=? ";

		Long cnt = super.getTaskCnt(sql,lev,WebTools.getCurrentBankId());
		
		return cnt;
	}

	// 待刻章的列表
	public List<Map<String, Object>> selectSealNewListMy(Page page) {
		int lev = bService.getBankLevel(WebTools.getCurrentBankId());
		
		String sql = " select tsn.*,tst.name tstname,tstc.name tstcname from t_seal_new tsn "
				+ " left outer join t_seal_type tst on tsn.seal_type_id=tst._id and tst.status=0 "
				+ " left outer join t_seal_type_config tstc on tsn.seal_type_config_id=tstc._id and tstc.status=0 "
				+ " left join t_seal_workflow tw on tsn.workflow_id=tw._id "
				+ " left join t_seal_workflow_module tm on tm.workflow_id=tw._id "
				+ " left join t_bank_level tl on tstc.verify_new=tl.name "
				+ " where tsn.flag in ('已审核通过','待刻制') and tl.sort>=? and tm.verify_bank_id=? and tsn.status=0 ";

		List<Map<String, Object>> list = super.jc.queryForList(sql,new Object[]{lev,WebTools.getCurrentBankId()}, page);

		return list;
	}

	// 刻章中 的列表,用于出厂后登记
	public List<Map<String, Object>> selectSealNewEngravingingList(Page page) {
		
		String sql = " select tsn.*,tst.name tstname,tstc.name tstcname from t_seal_new tsn "
				+ " left outer join t_seal_type tst on tsn.seal_type_id=tst._id and tst.status=0 "
				+ " left outer join t_seal_type_config tstc on tsn.seal_type_config_id=tstc._id and tstc.status=0 "
				+ " left join t_seal_new_factory_log tl on tl.seal_new_id=tsn._id and tl.flag='刻制中' "
				+ "where tsn.flag='刻制中' and tsn.status=0 and tl.user_bank_id=? ";

		List<Map<String, Object>> list = super.jc.queryForList(sql,new String[]{WebTools.getCurrentBankId()}, page);

		return list;
	}

	// 印章刻制生成
	@Transactional
	public void engraving(String sealnew_id, String factory,
			String factory_linkman, String factory_mobile) {
		t_seal_new sealNewDb = (t_seal_new) this.findObjById(sealnew_id,
				t_seal_new.class);
		sealNewDb.setFactory(factory);
		sealNewDb.setFactory_linkman(factory_linkman);
		sealNewDb.setFactory_mobile(factory_mobile);
		sealNewDb.setFlag("刻制中");

		t_seal_new_factory_log factoryLog = new t_seal_new_factory_log();
		factoryLog.setStart(new Timestamp(System.currentTimeMillis()));
		factoryLog.setSeal_new_id(sealNewDb.get_id());
		factoryLog.setUser_id(WebTools.getCurrentUserId());
		factoryLog.setUser_bank_id(WebTools.getCurrentBankId());
		factoryLog.setFlag("刻制中");

		ht.update(sealNewDb);
		ht.save(factoryLog);

	}

	// 出厂登记
	@Transactional
	public void back(String sealnew_id, String flag, String file_id,String save_user_id,String true_code, String note) {

		t_seal_new sealNew = super.findObjById(sealnew_id, t_seal_new.class);
		sealNew.setFile_id(file_id);

		// 查询刻制中的印章log
		String hql = "from t_seal_new_factory_log t where t.status=0 and t.seal_new_id=? and t.flag='刻制中'";
		t_seal_new_factory_log factLog = super.findObj(hql, sealnew_id);
		factLog.setFile_id(file_id);
		factLog.setNote(note);
		factLog.setEnd_date(new Timestamp(System.currentTimeMillis()));

		if ("不通过".equals(flag)) {
			factLog.setFlag("已作废");
			// 重新返厂刻制
			sealNew.setFlag("待刻制");

		} else if ("通过".equals(flag)) {
			factLog.setFlag("复核中");
			sealNew.setFlag("复核中");
			sealNew.setTemp_save_user_id(save_user_id);
			sealNew.setTrue_code(true_code);
			sealNew.setEngrave_user_bank_id(WebTools.getCurrentBankId());
			sealNew.setEngrave_user_id(WebTools.getCurrentUserId());
		}

		ht.update(sealNew);
		ht.update(factLog);
	}// # back

	@Task(code = "seal_engraving2", tip = "未完成的印章登记复核(@cnt)")
	public long selectSealNewEngravingVerifyingList() {
		String sql = "select count(*) cnt from t_seal_new t "
				+ " where t.status=0 and t.flag='复核中' and t.engrave_user_bank_id=? and t.engrave_user_id!=?";

		Long cnt = super.getTaskCnt(sql,WebTools.getCurrentBankId(),WebTools.getCurrentUserId());
			
		return cnt;
	}
	
	public List<Map<String, Object>> selectSealNewEngravingVerifyingList(
			Page page) {
		String sql = " select tsn.*,tst.name tstname,tstc.name tstcname from t_seal_new tsn "
				+ "left outer join t_seal_type tst on tsn.seal_type_id=tst._id and tst.status=0 "
				+ "left outer join t_seal_type_config tstc on tsn.seal_type_config_id=tstc._id and tstc.status=0 "
				+ "where tsn.flag='复核中' and tsn.engrave_user_bank_id=? and tsn.engrave_user_id!=? and tsn.status=0";

		List<Map<String, Object>> list = super.jc.queryForList(sql,new String[]{WebTools.getCurrentBankId(),WebTools.getCurrentUserId()}, page);

		return list;
	}

	// 查询 复核中的 印章日志
	public t_seal_new_factory_log getVerifyLog(String sealnew_id) {
		String hql = "from t_seal_new_factory_log t where t.status=0 and t.seal_new_id=? and t.flag='复核中'";
		t_seal_new_factory_log factLog = super.findObj(hql, sealnew_id);
		return factLog;
	}

	// 出厂登记复核
	@Transactional
	public void backVerify(String sealnew_id, String flag) {

		t_seal_new sealNew = super.findObjById(sealnew_id, t_seal_new.class);

		// 查询刻制中的印章log
		t_seal_new_factory_log factLog = getVerifyLog(sealnew_id);

		if ("不通过".equals(flag)) {
			factLog.setFlag("已作废");

			// 重新返厂刻制
			sealNew.setFlag("待刻制");

		} else if ("通过".equals(flag)) {
			sealNew.setFlag("刻制完成");
			factLog.setFlag("已完成");
			// 产生印章
			t_seal seal = new t_seal();
			seal.setBank_id(WebTools.getCurrentBankId());
			seal.setUse_bank_id(sealNew.getUse_bank_id());
			seal.setFlag("停用");
			seal.setFlag_stop("暂时停用");
			seal.setFlag_use("未领取");
			seal.setFlag_use_status("未安装 ");
			seal.setName(sealNew.getTitle());
			seal.setFile_id(sealNew.getFile_id());
			seal.setSeal_new_id(sealNew.get_id());
			seal.setUser_id(WebTools.getCurrentUserId());
			seal.setSave_user_id(sealNew.getTemp_save_user_id());
			seal.setTrue_code(sealNew.getTrue_code());
			ht.save(seal);
		}

		ht.update(sealNew);
		ht.update(factLog);
	}

	// 重新刻章
	@Transactional
	public void reSealNew(String sealnew_id) {
		t_seal_new sealNew = super.findObjById(sealnew_id, t_seal_new.class);

		String hql = "from t_seal_new_factory_log t where t.status=0 and t.seal_new_id=? and t.flag='已完成'";
		t_seal_new_factory_log factLog = super.findObj(hql, sealnew_id);
		if (ChkTools.isNotNull(factLog)) {
			factLog.setFlag("已作废");
			ht.update(factLog);
		}
		sealNew.setFlag("待刻制");

		ht.update(sealNew);
	}

	// 我的印章
	public List<Map<String, Object>> selectSealNewEngravingingLogList(String bank_id,String srh_name,Page page) {
		String sql = " select tsn.*,tst.name tstname,tstc.name tstcname,twk._id wk_id from t_seal_new tsn "
				+ "left outer join t_seal_new_factory_log t on t.seal_new_id=tsn._id "
				+ "left outer join t_seal_type tst on tsn.seal_type_id=tst._id and tst.status=0 "
				+ "left outer join t_seal_type_config tstc on tsn.seal_type_config_id=tstc._id and tstc.status=0 "
				+ " left outer join t_seal_workflow twk on tsn.workflow_id=twk._id and twk.status=0 and twk.type='新章审批' "
				+ "where tsn.user_id=? and tsn.title like ? and tsn.status=0 order by tsn.created desc";
		
		List<String> params = new ArrayList<String>();
		params.add(WebTools.getCurrentUserId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and tsn.title like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}

		List<Map<String, Object>> list = jc.queryForList(sql, params.toArray(),
				page);
		for (Map<String, Object> map : list) {
			String wk_id = map.get("wk_id")+"";
			String sq = "select t.*,tb.name from t_seal_workflow_module t "
					+ " left join t_bank tb on t.verify_bank_id=tb._id where t.workflow_id=?";
			List<Map<String, Object>> l = jt.queryForList(sq, wk_id);
			String wk_note = "";
			for (Map<String, Object> m : l) {
				wk_note += m.get("name")+"["+m.get("flag")+" ";
				if((m.get("verify_time")+"").length()>10){
					wk_note += m.get("verify_time").toString().substring(0,10)+"];";
				}else{
					wk_note += "];";
				}
			}
			map.put("wk_note", wk_note);
		}
		System.err.println("----"+list);
		return list;
	}
	
	public static void main(String[] args) {

	}

	//印章编号唯一
	public boolean checkUniqueCode(String seal_new_id, String code) {
		String sql = "select * from t_seal_new t where t.true_code=? and t._id!=? and t.status=0 ";
		List<String> params = new ArrayList<String>();
		params.add(code);
		if (ChkTools.isNull(seal_new_id)) {
			sql = sql.replace("and t._id!=?", "");
		} else {
			params.add(seal_new_id);
		}
		List<Map<String, Object>> list = jt.queryForList(sql,params.toArray());
		
		if(list.size()>0)
			return false;
		return true;
	}
}
